package com.atguigu.common.valid;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;
import java.util.Set;

/**
 * @title: LIstValueConstraintValidator
 * @Author syh
 * @Date: 2022/6/15 21:07
 * @Version 1.0
 */

public class LIstValueConstraintValidator implements ConstraintValidator<ListValue, Integer> {

    private Set<Integer> set = new HashSet<>();

    /**
     * 初始化方法
     *
     * @param constraintAnnotation
     */
    @Override
    public void initialize(ListValue constraintAnnotation) {
        int[] vals = constraintAnnotation.vals();
        if (vals.length > 0) {
            for (int val : vals) {
                set.add(val);
            }
        }
    }

    /**
     * 是否校验成功
     *
     * @param integer                    需要校验的值
     * @param constraintValidatorContext 校验的上下文信息
     * @return 是否校验通过
     */
    @Override
    public boolean isValid(Integer integer, ConstraintValidatorContext constraintValidatorContext) {
        if (null != set && !set.isEmpty() && set.size() > 0) {
            return set.contains(integer);
        }
        return false;
    }
}
